package com.wswy.wzcx.widget.drawable

import android.graphics.*
import android.util.Log
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils

class GuideArrowDrawable() : BaseDrawable() {

    companion object {
        private const val TAG = "GuideArrowDrawable"
    }

    private val rectF = RectF()

    private val path = Path()

    private val currArrowRect = RectF()

    private var startColor:Int = 0
    private var endColor:Int = 0

    override fun onBoundsChange(bounds: Rect?) {
        super.onBoundsChange(bounds)
        rectF.set(rect)

        rectF.inset(SizeUtils.dp2px(10f).toFloat(),SizeUtils.dp2px(15f).toFloat())



        paint.style = Paint.Style.FILL

        if(!currArrowRect.isEmpty) {
            val arrowUp = ScreenUtils.getScreenHeight()/2 > currArrowRect.bottom
            update(arrowUp)
        }
    }

    override fun draw(canvas: Canvas?) {

        if (!path.isEmpty ){

            canvas?.run {
                val count = save()
                clipPath(path)
                drawPaint(paint)
                restoreToCount(count)
            }
        }

    }



    fun setArrowAnchor(r: RectF,arrowUp: Boolean,startColor:Int,endColor:Int){
        currArrowRect.set(r)

        this.startColor = startColor
        this.endColor = endColor

        if (!rectF.isEmpty){
            update(arrowUp)
        }

        invalidateSelf()
    }


    private fun update(arrowUp:Boolean){
        path.reset()

        if (startColor == 0 || endColor == 0){
            return
        }

        val gradient = LinearGradient(0f, 0f, rectF.width(), rectF.height(),
                intArrayOf(startColor,  endColor), null, Shader.TileMode.CLAMP)

        paint.shader = gradient

        //圆角矩形
        path.addRoundRect(rectF,SizeUtils.dp2px(24f).toFloat()
                ,SizeUtils.dp2px(24f).toFloat(),Path.Direction.CW)

        //矩形 箭头居中
        if (arrowUp){

            path.moveTo(currArrowRect.centerX()-20,rectF.top)

            path.lineTo(currArrowRect.centerX(),rectF.top-30)
            path.lineTo(currArrowRect.centerX()+20,rectF.top)

        }else{
            path.moveTo(currArrowRect.centerX()-20,rectF.bottom)

            path.lineTo(currArrowRect.centerX(),rectF.bottom+30)
            path.lineTo(currArrowRect.centerX()+20,rectF.bottom)
        }

    }

}